<?php
/**
 * 推送消息
 */
$log_file = 'wx_push_message';
require dirname(__FILE__) . '/base.php';
$transaction = new \Base\BaseOrmModel();
$transaction->beginTransaction();
try {
    //业务消息
    $notice_sql = "SELECT
                        m.id,
                        m.title,
                        m.content,
                        m.business_id,
                        m.business_amount,
                        m.business_status,
                        m.type,
                        m.receiver_id,
                        tc.open_id
                    FROM
                        t_message AS m
                    LEFT JOIN t_customer AS tc ON tc.id = m.receiver_id
                    WHERE
                        m.is_system_notice = 0
                    AND m.`status` = 0
                    AND tc.`is_del` = 0
                    AND tc.open_id != '';";
    $notice_data = $transaction->_fetch($notice_sql,1);
    if(count($notice_data)>0){
        //推送微信消息（业务消息）
        foreach($notice_data as $v){
            collageData($v['open_id'],$v['title'],$v['content'],$v['receiver_id'],$v['type'],$v['business_amount'],$v['business_id'],$v['business_status']);
            $update_sql = "update t_message set `status` = 1 where id = {$v['id']}";
            $res = $transaction->execute($update_sql);
        }
    }

    //系统通知
    /*$system_sql = "SELECT
                        m.id,
                        m.title,
                        m.content,
                        m.insert_time as time,
                        tc.open_id
                    FROM
                        t_message AS m,
                        t_customer AS tc
                    WHERE
                        m.is_system_notice = 1
                    AND m.`status` = 0
                    AND tc.`is_del` = 0
                    AND tc.open_id != '' ;";
    $system_data = $transaction->_fetch($system_sql,1);
    $system_array = array();
    if(count($system_data)>0){
        //推送微信消息（业务消息）
        foreach($system_data as $v){
            systenDate($v['open_id'],$v['title'],$v['content'],$v['time']);
            $system_array[] = $v['id'];
        }
        $system_ids = implode(',',array_unique($system_array));
        $update_sql = "update t_message set `status` =1 where id in ({$system_ids})";
        $res = $transaction->execute($update_sql);
    }*/
    $transaction->commit();
} catch (Exception $e) {
    $transaction->rollBack();
    echo $e->getMessage();
    \Util\LogUtil::log($log_file, $e->getMessage());
    exit;
}

/**
 * 系统通知
 * @param $open_id
 * @param $title
 * @param $content
 * @param $time
 */
function systenDate($open_id,$title,$content,$time){
    $data = array(
        'touser' => $open_id,
        'template_id' => \Util\Config::get('weixin_template_achievement', 'Env'),
        'url' => \Util\Config::get('weixin_domain', 'Env') . '/message/list',
        'topcolor' => "#a0dca0",
        'data' => array(
            'first' => array(
                'value' => urlencode($content),
            ),
            'keyword1' => array(
                'value' => urlencode($title),
            ),
            'keyword2' => array(
                'value' => urlencode($time),
            ),
            'remark' => array(
                'value' => urlencode(""),
            ),
        )
    );
    //发送消息
    if (!empty($data) && \Util\Config::get('env', 'Env') != 'dev') {
        send_message(urldecode(json_encode($data)));
    }
}

/**
 * 业务消息
 * @param $open_id
 * @param $title
 * @param $content
 * @param $receiver_id
 * @param $type
 * @param $amount
 * @param $id
 */
function collageData($open_id,$title, $content, $receiver_id, $type, $amount, $id,$status)
{
    $customer_orm = new \Orm\Customer\CustomerClass();
    $customer_orm->loadById($receiver_id);
    $now_time = date('Y-m-d H:i:s', time());
    $status_remark = '';
    $data = array();
    //处理状态
    switch ($status){
        case \Orm\Bill\BillClass::STATUS_CHECK:
            $status_remark = '申请已提交';
            break;
        case \Orm\Bill\BillClass::STATUS_CONFIRM:
            $status_remark = '成功';//审核通过
            break;
        case \Orm\Bill\BillClass::STATUS_CANCELLATION:
            $status_remark = '审核未通过';
            break;
        default;
    }
    $tmp_url = '';
    //订单消息请求体
    if ($type == \Orm\Message\MessageClass::TYPE_PURCHASE_ORDER || $type == \Orm\Message\MessageClass::TYPE_PICK_ORDER || $type == \Orm\Message\MessageClass::TYPE_SHOP_ORDER) {
        if ($type == \Orm\Message\MessageClass::TYPE_PICK_ORDER && $id != '') {
            $tmp_url = \Util\Config::get('weixin_domain', 'Env') . '/my/pick-up-order-detail/id/' . $id;
        } elseif ($type == \Orm\Message\MessageClass::TYPE_PURCHASE_ORDER && $id != '') {
            $tmp_url = \Util\Config::get('weixin_domain', 'Env') . '/purchase/detail/id/' . $id;
        }
        $data = array(
            'touser' => $open_id,
            'template_id' => \Util\Config::get('weixin_template_order', 'Env'),
            'url' => $tmp_url,
            'topcolor' => "#a0dca0",
            'data' => array(
                'first' => array(
                    'value' => urlencode($content),
                ),
                'keyword1' => array(
                    'value' => urlencode($title),
                ),
                'keyword2' => array(
                    'value' => urlencode($now_time),
                ),
                'remark' => array(
                    'value' => urlencode(""),
                ),
            )
        );
    } else if ($type == \Orm\Message\MessageClass::TYPE_RECHARGE) {//货款充值请求体
        $data = array(
            'touser' => $open_id,
            'template_id' => \Util\Config::get('weixin_template_recharge', 'Env'),
            'url' => \Util\Config::get('weixin_domain', 'Env') . '/my/wallet',
            'topcolor' => "#a0dca0",
            'data' => array(
                'first' => array(
                    'value' => urlencode($content),
                ),
                'accountType' => array(
                    'value' => urlencode('充值时间'),
                ),
                'account' => array(
                    'value' => urlencode($now_time),
                ),
                'amount' => array(
                    'value' => urlencode($amount),
                ),
                'result' => array(
                    'value' => urlencode($status_remark),
                ),
                'remark' => array(
                    'value' => urlencode(""),
                ),
            )
        );
    } else if ($type == \Orm\Message\MessageClass::TYPE_BALANCE) {//余额提现请求体
        $data = array(
            'touser' => $open_id,
            'template_id' => \Util\Config::get('weixin_template_balance', 'Env'),
            'url' => \Util\Config::get('weixin_domain', 'Env') . '/my/wallet',
            'topcolor' => "#a0dca0",
            'data' => array(
                'first' => array(
                    'value' => urlencode($content),
                ),
                'keyword1' => array(
                    'value' => urlencode($amount),
                ),
                'keyword2' => array(
                    'value' => urlencode($now_time),
                ),
                'keyword3' => array(
                    'value' => urlencode($status_remark),
                ),
                'remark' => array(
                    'value' => urlencode(""),
                ),
            )
        );
    } else if ($type == \Orm\Message\MessageClass::TYPE_ACHIEVEMENT) {//业绩返点请求体
        $data = array(
            'touser' => $open_id,
            'template_id' => \Util\Config::get('weixin_template_achievement', 'Env'),
            'url' => \Util\Config::get('weixin_domain', 'Env') . '/my/performance',
            'topcolor' => "#a0dca0",
            'data' => array(
                'first' => array(
                    'value' => urlencode($content),
                ),
                'keyword1' => array(
                    'value' => urlencode($title),
                ),
                'keyword2' => array(
                    'value' => urlencode($now_time),
                ),
                'remark' => array(
                    'value' => urlencode(""),
                ),
            )
        );
    }
    //发送消息
    if (!empty($data) && \Util\Config::get('env', 'Env') != 'dev') {
        send_message(urldecode(json_encode($data)));
    }
}

/**
 * @param $data
 * @return mixed
 * 发送系统消息
 */
function send_message($data)
{
    $access_token = get_access_token();
    $url = \Util\Config::get('send_message_url', 'Common') . 'access_token=' . $access_token;
    $res = http_request($url, $data);
    return json_decode($res, true);
}

/**
 * @return mixed
 * 获取微信access_token
 */
function get_access_token()
{
    $app_id = \Util\Config::get('weixin_appid', 'Env');
    $app_secret = \Util\Config::get('weixin_appsecret', 'Env');
    $fileName = \Util\Config::get('get_access_token_url', 'Common') . 'appid=' . $app_id . '&secret=' . $app_secret;
    $res = file_get_contents($fileName);
    $res = json_decode($res, true);
    $access_token = isset($res['access_token']) ? $res['access_token'] : '';
    return $access_token;
}

/**
 * @param $url
 * @param null $data
 * @return mixed|string
 * 发送消息请求
 */
function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);//需要获取的URL地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);//禁用后cURL将终止从服务端进行验证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);//启用时会发送一个常规的POST请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//	全部数据使用HTTP协议中的"POST"操作来发送
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。 returntransfer
    $output = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'Error' . curl_error($curl);
    }
    curl_close($curl);
    return $output;
}



